package com.xsp.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xsp.entity.CommonResult;
import com.xsp.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xsp
 * @date 2024/3/10
 * @desc
 */
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        CommonResult result = null;
        try{
            JWTUtil.verify(token);
            return true;
        } catch(SignatureVerificationException e) {
            result  = CommonResult.error("签名不一致");
        }catch(TokenExpiredException e) {
            result  = CommonResult.error("令牌过期");
        }catch(AlgorithmMismatchException e) {
            result  = CommonResult.error("算法不匹配");
        }catch(InvalidClaimException e) {
            result  = CommonResult.error("失效的payload");
        }catch(Exception e) {
            result  = CommonResult.error("失效的token");
        }
        String json = new ObjectMapper().writeValueAsString(result);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(json);
        // 拦截
        return false;
    }
}
